package com.zzj.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.zzj.base.Result;
import com.zzj.service.RedisService;
import com.zzj.utils.JWTUtil;
import com.zzj.utils.Utils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.Map;

import static com.zzj.base.ResultCode.NO_LOGGED_IN;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");
        String queryString = request.getQueryString();
        if (queryString != null && token == null) {
            Map<String, String> stringStringMap = Utils.parseQueryString(queryString);
            token = stringStringMap.get("Authorization");
        }

        if (token == null) {
            write(response, new Result(NO_LOGGED_IN, "未登录"));
            return false;
        }
        // token是否在黑名单中
        boolean blacklist = redisService.isBlacklist(token);
        if (blacklist) {
            write(response, Result.error("token已注销"));
            return false;
        }
        // token 在JWT是否有效
        boolean verifyResult = JWTUtil.verify(token);
        if (!verifyResult) {
            write(response, new Result(NO_LOGGED_IN, "未登录"));
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    private void write(ServletResponse response, Result result) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        httpResponse.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSONObject.toJSONString(result));
    }

}
